package com.fingard.dsp.bank.directbank.gac01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.net.ssl.SSLContext;
import java.util.Date;

/**
 * @author Parker on 2020-06-18.
 * @version 1.0
 */
public class GAC01Base extends DirectBase {
    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    //http格式
    protected String[] sendToBank(String pReqStr, String transType, String commandCode) throws Exception {
        String[] retStr = new String[]{"", ""};
        if (StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, pReqStr, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }

        String url = bankFront.serverURL;
        WriteBankLogStep2(pReqStr);
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
        httpClient.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, 30000);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,getCharset());

        NameValuePair[] pair = new NameValuePair[] { new NameValuePair("_USER_REQUEST_DATA", pReqStr) };
        postMethod.addParameters(pair);

        int result = httpClient.executeMethod(postMethod);

        if (HttpStatus.SC_OK != result) {
            retStr[0] = "MessageHandlerService sendMessage fail";
        } else {
            retStr[1] = postMethod.getResponseBodyAsString();
            WriteBankLogStep3(retStr[1]);
        }

        return retStr;
    }


    protected void writeCommonHeader(XmlTextWriter xmlTextWriter) {
        xmlTextWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
    }

}
